package breeze.tool.life.broadcasts;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.appwidget.AppWidgetManager;
import android.widget.RemoteViews;
import breeze.tool.life.R;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.content.ComponentName;
import android.content.Intent;
import breeze.tool.life.services.WeatherUpdateServics;
import breeze.tool.life.module.Weather3DBean;
import breeze.tool.life.utils.AppWeatherUtils;
import brz.breeze.app_utils.BAppUtils;

public class Weather3DWidget extends AppWidgetProvider {

    /*
	 *@author BREEZE
	 *@date 2022-02-06 18:04:45
	 */
    public static final String TAG = "Weather3DWidget";

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
		super.onUpdate(context, appWidgetManager, appWidgetIds);
		init(context);
	}

	@Override
	public void onEnabled(Context context) {
		super.onEnabled(context);
		init(context);
	}

	private void init(final Context context) {
		ServiceConnection scon = new ServiceConnection(){

			@Override
			public void onServiceConnected(ComponentName p1, final IBinder p2) {
				BAppUtils.execute(new Runnable(){
						@Override
						public void run() {
							WeatherUpdateServics.MBinder service = (WeatherUpdateServics.MBinder) p2;
							WeatherUpdateServics service2 = service.getService();
							final Weather3DBean bean = service2.get3DBean();
							if (null != bean || "200".equals(bean.getCode())) {
								Weather3DBean.Daily daybean = bean.getDaily().get(1);
								ComponentName cn = new ComponentName(context, Weather3DWidget.class);
								AppWidgetManager awm = AppWidgetManager.getInstance(context);
								RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.layout_widget_weather3d);
								rv.setImageViewBitmap(R.id.widget_3d_icon, AppWeatherUtils.getWeatherIcon(context, daybean.getIconDay()));
								rv.setTextViewText(R.id.widget_3d_weather, daybean.getTextDay());
								rv.setTextViewText(R.id.weather_3d_wind, daybean.getWindDirDay());
								rv.setTextViewText(R.id.weather_3d_temp, daybean.getTempMin() + "/" + daybean.getTempMax() + "℃");
								awm.updateAppWidget(cn, rv);
							}
						}
					});
			}

			@Override
			public void onServiceDisconnected(ComponentName p1) {
			}

		};
		Intent intent = new Intent(context, WeatherUpdateServics.class);
		context.startService(intent);
		context.getApplicationContext().bindService(intent, scon, 1);
	}

}
